In this blog I will told you that how to implement exception handling mechanism in c#. Here I will describe certain keywords which are used while we implementing concept of exception handling.
1. try
We enclose a block of code that has the potential of throwing exception within a try block. A catch handler associated with the exception that is thrown catches the exception. There can be one or more catch handler for single try and each catch handler can be associated with a specific exception type that it can handle. finally block contains that piece of code which will always executed in all cases whether exception is raised or not such as cleanup code or disconnection connection from server. We use throw keyword for throwing exception at certain condition which is caught by try block.
Syntax for exception handling
try
{
//Code that can encounters errors and raise exceptions.
}
catch
{
//Code that handles errors and exceptions.
}
finally
{
//Code that perform cleanup and executes both on normal execution
//path as well as in case of error occurs.
}
Following example will demonstrate use of try-catch-finally block and throw keyword.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ExceptionHandling
{
class Program
{
static void Main(string[] args)
{
try
{
//Write down statements to generate exception.
Console.WriteLine("Here is demo of exception handling......!");
throw new Exception("Oops..! Exception is thrown....");
}
catch(Exception ex)
{
//Dispaly the error message.
Console.WriteLine("Caught Exception : {0}", ex.Message);
}
finally
{
//This is a finally block which always executed.
Console.WriteLine("Ops Finally program end.");
}
}
}
}
Output of following code snippet is as follows.
Here is demo of exception handling......!
Caught Exception: Oops..! Exception is thrown....
Ops finally program end.
Anonymous User
16-Mar-2019Thakn You for sharing.
Samuel Fernandes
31-Jul-2017I am grateful to you, for sharing a post like this.